﻿using System.Linq;
using DAL;
using Model;
using WinForm.Modules;
using CityContacts = Model.ViewModel.CityContacts;

namespace WinForm.Details
{
    public partial class CityContactsAddEditDetail : DetailBase
    {
        //public CityContactsAddEditDetail(ModuleBase praentModule,CityContacts obj):base(praentModule)
        //{
        //    InitializeComponent();
        //}

        public CityContacts CurrentObject { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="praentModule"></param>
        /// <param name="cityContact">添加时值为null，编辑时值为要编辑的对象</param>
        public CityContactsAddEditDetail(ModuleBase praentModule, CityContacts cityContact)
            : base(praentModule)
        {
            InitializeComponent();
            cbCity.Items.Clear();

            CurrentObject = cityContact;
            
            cbCity.DataSource = DbHelper.Db.Citys.ToList();
            cbCity.DisplayMember = "CityName";
            cbCity.ValueMember = "CityId";

            if (cityContact == null) return;

            var cityItem = DbHelper.Db.Citys.Where(p => p.CityNo == cityContact.CityNo);
            cbCity.SelectedValue = cityItem.First().CityId;
            ;
            tbContactName.Text = cityContact.Name;
            tbCellPhone.Text = cityContact.CellPhone;
            tbTellPhone.Text = cityContact.TellPhone;
            tbMemo.Text = cityContact.Memo;
        }


        /// <summary>
        /// 保存数据，需要覆盖
        /// </summary>
        protected override void SaveData()
        {
            var city = DbHelper.Db.Citys.Find(cbCity.SelectedValue);
            var contact = new Contacts
            {
                Name = tbContactName.Text.Trim(),
                CellPhone = tbCellPhone.Text.Trim(),
                TellPhone = tbTellPhone.Text.Trim(),
                Memo = tbMemo.Text.Trim()
            };
            Model.CityContacts newCityContact = new Model.CityContacts
            {

                    City = city,
                    Contacts = contact
                };
            if (CurrentObject == null)
            {
                
                DAL.CityContacts.Add(newCityContact);
            }
            else
            {
                newCityContact.CityContactsId = CurrentObject.CityContactsId;
                DAL.CityContacts.Update(newCityContact);
            }
            
            
        }

        /// <summary>
        /// 清空控件中的数据,需要覆盖
        /// </summary>
        protected override void ClearData()
        {
            tbContactName.Text = string.Empty;
            tbCellPhone.Text= string.Empty;
            tbTellPhone.Text= string.Empty;
            tbMemo.Text = string.Empty;
        }

    }
}
